// 每个依赖的唯一标识
let id = 0;
// 收集到的依赖
export class Dep {
	constructor() {
		this.id = id++;
		// 保存对应的watcher,不能重复
		this.watcherId = new Set();
		// 一个dep对应对应多个watcher
		this.subs = [];
	}
	addSub(watcher) {
		const { id } = watcher;
		// 保存没有保存过的watcher
		if (!this.watcherId.has(id)) {
			this.watcherId.add(id);
            this.subs.push(watcher);
		}
	}
	// 保存数据依赖的watcher
	depend() {
		// 让watcher记住当前的依赖
		Dep.target.addDep(this);
	}
	// 通知对应的watcher更新视图
	notify() {
		this.subs.forEach((watcher) => {
			watcher.update();
		});
	}
}

// 保存watcher的栈
const stack = [];

// Dep.target 指向栈顶的watcher
// 存收集的watcher到栈中
export function pushWatcher(watcher) {
	Dep.target = watcher;
	stack.push(watcher);
}

// 移除掉使用过的watcher
export function popWatcher() {
	stack.pop();
	Dep.target = stack[stack.length - 1];
}
